package com.moli.config;

import com.moli.filter.JwtAuthenticationTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @Author： XC
 * @Date： 2023-06-04 10:25
 * @Description： 安全配置类
 */

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	/*
	 * AuthenticationManager（接口）是认证相关的核心接口
	 * AuthenticationManager一般不直接认证，AuthenticationManager接口的常用实现类ProviderManager 内部会维护一个List列表，
	 * 存放多种认证方式，实际上这是委托者模式的应用（Delegate）。也就是说，核心的认证入口始终只有一个：AuthenticationManager，
	 * 不同的认证方式：用户名+密码（UsernamePasswordAuthenticationToken），邮箱+密码，手机号码+密码登录则对应了三个AuthenticationProvider。
	 */
	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Resource
	private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

	//认证失败处理器
	@Resource
	AuthenticationEntryPoint authenticationEntryPoint;

	//授权失败处理器
	@Resource
	AccessDeniedHandler accessDeniedHandler;


	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
				//关闭csrf
				.csrf().disable()
				//不通过Session获取SecurityContext，因为不是同一个会话 也就不会通过session生成SecurityContext对象
				//前后端分离  基本用不上session
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				//认证配置
				.authorizeRequests()
				// 对于登录接口 允许匿名访问 没登录也能访问  登录就不能访问了  permitAll() 就都可以访问了
				.antMatchers("/user/login").anonymous()
//                //注销接口需要认证才能访问
//                .antMatchers("/logout").authenticated()
//                .antMatchers("/user/userInfo").authenticated()
//                .antMatchers("/upload").authenticated()
				// 除上面外的所有请求全部不需要认证即可访问
				.anyRequest().authenticated();

		//配置异常处理器
		http.exceptionHandling()
				.authenticationEntryPoint(authenticationEntryPoint)
				.accessDeniedHandler(accessDeniedHandler);
		//关闭默认的注销功能
		http.logout().disable();
		//把jwtAuthenticationTokenFilter添加到SpringSecurity的过滤器链中
		//把jwtAuthenticationTokenFilter过滤器添加到UsernamePasswordAuthenticationFilter之前
		http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
		//允许跨域
		http.cors();
	}

	//创建BCryptPasswordEncoder注入容器
	//注入之后 有关密码的加密和校验都会用到BCryptPasswordEncoder(security提供的)
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}
